package com.llkj.qingnianguoxue.circle;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.llkj.qingnianguoxue.R;
import com.llkj.qingnianguoxue.adapter.InterestCircleAdapter;
import com.llkj.qingnianguoxue.base.BaseActivity;
import com.llkj.qingnianguoxue.base.ConstantUserInfo;
import com.llkj.qingnianguoxue.base.MyApplication;
import com.llkj.qingnianguoxue.bean.CircleListBean;
import com.llkj.qingnianguoxue.http.HttpMethod;
import com.llkj.qingnianguoxue.login.LoginActivity;
import com.llkj.qingnianguoxue.util.DialogUtil;
import com.llkj.qingnianguoxue.util.DisplayUtil;
import com.llkj.qingnianguoxue.util.GsonUtil;
import com.llkj.qingnianguoxue.util.PayMethodViewUtil;
import com.llkj.qingnianguoxue.util.RxBus;
import com.llkj.qingnianguoxue.util.StringUtils;
import com.llkj.qingnianguoxue.util.ToastUtil;
import com.llkj.qingnianguoxue.util.helper.LoadDataHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * 搜索圈子
 */
public class SearchCircleActivity extends BaseActivity implements View.OnClickListener, BaseQuickAdapter.RequestLoadMoreListener,
        LoadDataHelper.LoadMoreListener, SwipeRefreshLayout.OnRefreshListener, PayMethodViewUtil.PaySuccessListener {
    private SwipeRefreshLayout refreshLayout;
    private ImageView ivCancel;//取消
    private TextView tvSearch;
    private EditText etSearch;//搜索关键字
    private RecyclerView lvResult;//结果
    private InterestCircleAdapter interestCircleAdapter;
    private List<CircleListBean.CircleBean> mCircleData;
    private String mKeyword;
    private int totalSize, mPage, mCurrentPosition;
    private PayMethodViewUtil payMethodViewUtil;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_circle);

        payMethodViewUtil = new PayMethodViewUtil(this, this);
        initView();
        initListener();

    }

    private void initView() {
        RelativeLayout rlTop = findViewById(R.id.rl_top);
        initStatusbar(TSATUSBAR_TYPE_BLACK_TEXT, rlTop, R.color.gray_bar);
        ivCancel = (ImageView) findViewById(R.id.iv_cancel);
        tvSearch = (TextView) findViewById(R.id.tv_search);
        etSearch = (EditText) findViewById(R.id.et_search);
        etSearch.setText(mKeyword);

        refreshLayout = (SwipeRefreshLayout) findViewById(R.id.refresh_layout);
        refreshLayout.setColorSchemeResources(R.color.blue3989ff);
        lvResult = (RecyclerView) findViewById(R.id.recyclerView);
        lvResult.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        int padding = DisplayUtil.dip2px(this, 10);
        lvResult.setPadding(padding, 0, padding, padding);
        lvResult.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));

        mCircleData = new ArrayList<>();
        interestCircleAdapter = new InterestCircleAdapter(R.layout.item_interest_circle, mCircleData, null);
        interestCircleAdapter.setType(3);
        lvResult.setAdapter(interestCircleAdapter);
    }

    private void initListener() {
        refreshLayout.setOnRefreshListener(this);
        interestCircleAdapter.setOnLoadMoreListener(this);
        ivCancel.setOnClickListener(this);
        tvSearch.setOnClickListener(this);
        lvResult.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                CircleListBean.CircleBean item = mCircleData.get(i);
                if ("1".equals(item.getIs_add())) {//已加入
                    MyChatActivity.startGroupChat(SearchCircleActivity.this, item.getHx_id(), item.getId(), item.getName());
                }
            }
        });

        lvResult.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                clickViewCallback(i);
            }
        });


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_cancel://取消
                finish();
                break;
            case R.id.tv_search:
                String word = etSearch.getText().toString();
                if (!StringUtils.isEmpty(word)) {
                    if (StringUtils.isContaintSymbol(word)) {
                        ToastUtil.makeLongText(SearchCircleActivity.this, "对不起，请不要输入特殊字符");
                        return;
                    }
                    mKeyword = word;
                    loadWaitDialog();
                    onRefresh();
                } else {
                    ToastUtil.makeLongText(SearchCircleActivity.this, "请输入搜索关键字");
                }
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        payMethodViewUtil.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void dialogRightBtn() {
        super.dialogRightBtn();
        startActivity(LoginActivity.class);
    }

    public void clickViewCallback(int position) {
        CircleListBean.CircleBean item = mCircleData.get(position);
        if (!"1".equals(item.getIs_add())) {//未加入
            boolean isLogin = MyApplication.getInstance().sputil.getBoolean(ConstantUserInfo.ISLOGIN);
            if (!isLogin) {
                dialogConfirm(null, null, null, null).show();
                return;
            }
            //稍后处理，需在支付完成后
            mCurrentPosition = position;
            final CircleListBean.CircleBean circleBean = mCircleData.get(mCurrentPosition);
            String note = "加入圈子需支付" + circleBean.getPrice() + "元\n费用时限" + circleBean.getCycle() + "天";
            DialogUtil.dialogConfirm(this, note, null, "考虑一下", "支付", new DialogUtil.DialogClickListener() {
                @Override
                public void dialogClick(int type) {
                    if (type == 1) {
                        payMethodViewUtil.showPayMethodDialog(circleBean.getPrice());
                    }
                }
            }).show();
        }
    }

    @Override
    public void paySucessResponse(int type) {
//        if(type==0){//三方支付
//
//        }else{//余额
//
//        }
        //处理三方支付成功后的操作
        CircleListBean.CircleBean item = mCircleData.get(mCurrentPosition);
        loadWaitDialog();
        HttpMethod.addGroup(this, this, item.getHx_id(), item.getPrice(), item.getCycle(), item.getId(), String.valueOf(type));
    }

    @Override
    public void onLoadMore() {
        mPage++;
        getCircleData();
    }

    @Override
    public void onRefresh() {
        mPage = 1;
        getCircleData();
    }

    @Override
    public void onLoadMoreRequested() {
        LoadDataHelper.loadMoreRequest(this, interestCircleAdapter, null, lvResult, totalSize);
    }

    /**
     * 6.2圈子搜索数据
     */
    private void getCircleData() {
        HttpMethod.circleSearch(this, this, mKeyword, String.valueOf(mPage));
    }

    @Override
    protected void onhttpSuccess(String data, int method) {
        super.onhttpSuccess(data, method);
        if (method == HttpMethod.HTTP_CIRCLE_SEARCH) {
            CircleListBean circleListBean = GsonUtil.GsonToListBean(data, CircleListBean.class);
            if (circleListBean != null) {
//                totalSize = Integer.parseInt(circleListBean.getNum());
                if (mPage == 1) {
                    mCircleData.clear();
                    LoadDataHelper.refreshComplete(interestCircleAdapter, mCircleData, refreshLayout, lvResult);
                } else {
                    interestCircleAdapter.setEnableLoadMore(true);
                    interestCircleAdapter.loadMoreComplete();
                }
                mCircleData.addAll(circleListBean.getList());
                interestCircleAdapter.notifyDataSetChanged();
                if (mCircleData.size() == 0) {
                    ToastUtil.makeShortText(this, "没有找到相应内容");
                }
            }
        } else if (method == HttpMethod.HTTP_CIRCLE_ADD_GROUP) {//6.4加入圈子
            ToastUtil.makeLongText(this, "加入成功");
            CircleListBean.CircleBean circleBean = mCircleData.get(mCurrentPosition);
            circleBean.setIs_fans("1");
            interestCircleAdapter.notifyItemChanged(mCurrentPosition);

        } else if (method == HttpMethod.HTTP_CIRCLE_ADD_GROUP) {//6.4加入圈子
            ToastUtil.makeLongText(this, "加入成功");
            CircleListBean.CircleBean circleBean = mCircleData.get(mCurrentPosition);
            circleBean.setIs_add("1");
            interestCircleAdapter.notifyItemChanged(mCurrentPosition);
            RxBus.getInstance().post(ConstantUserInfo.REFRESH_CIRCLE);
        }
    }
}
